
from meta_service.store import ArxivPaper
from meta_service.tag import ArxivTag
import os
from datetime import datetime

def detect_pyfile_absdir():
    """
    获取当前py文件所处的目录
    """
    this_pyfile_abs_path = str(__file__)
    # 获取当前目录
    this_pyfile_dir = os.path.dirname(this_pyfile_abs_path)
    return this_pyfile_dir


MEETING_LIST_DIR = detect_pyfile_absdir()
MEETING_LIST_PATH = os.path.join(MEETING_LIST_DIR,"meeting.list")
CURRENT_YEAR = int(datetime.now().year)

def load_list_file(file_path:str):
    all = None
    with open(file_path,"r",encoding="utf-8") as fp:
        all = fp.readlines()
        all = [ one.split("\n")[0] for one in all ]
        all = [ one.strip() for one in all ]
        all = [ one for one in all if len(one) > 0 ]
    return [] if all is None else all

def gen_years_list(begin_year:int,end_year:int):
    byear = min(begin_year,end_year)
    eyear = max(begin_year,end_year)
    lis = [ int(year) for year in range(byear,eyear+1) ]
    lis.reverse()
    return lis

MEETING_LIST = load_list_file(MEETING_LIST_PATH)
MEETING_YEAR = gen_years_list(2010,CURRENT_YEAR+2)


def check_meeting_in_comment(entry_id:str):
    paper = ArxivPaper(entry_id)
    comment = paper.get_comment()
    print(f"comment = {comment}")
    selected_meeting = None
    for met in MEETING_LIST:
        if met in comment:
            selected_meeting = met
            break
    if selected_meeting is None:
        return None,None
    # 年份很可能不准确
    selected_year = None
    for year in MEETING_YEAR:
        if str(year) in comment:
            selected_year = year
            break
    return selected_meeting,selected_year


def CheckMeetingInComment(entry_id:str):
    """
    从comment字段中搜索是否存在 meeting.list 中列举的会议, 并添加为 Tag
    """
    met,year = check_meeting_in_comment(entry_id)
    tager = ArxivTag(entry_id)
    if isinstance(met,str):
        if isinstance(year,int):
            tager.AddTag("Meeting",f"{met}.{year}")
        else:
            tager.AddTag("Meeting",f"{met}")
    else:
        tager.AddTag("Meeting","<UnKnown>")
    pass

